#include "bridge_service.h"
#include <stdio.h>
#include <stdlib.h>
#include <libubus.h>
#include <libubox/uloop.h>
#include <libubox/list.h>
#include <libubox/blobmsg_json.h>
#include <cjson/cJSON.h>
#include "comm.h"
#include "data_type.h"
#include "trans_util.h"

extern t_RunCfg runCfg;
struct blob_buf bb;

static const struct blobmsg_policy bridge_info_policy[] = {
    [0] = { .name = "deviceMode",           .type = BLOBMSG_TYPE_STRING },
    [1] = { .name = "wirelessMode",        .type = BLOBMSG_TYPE_STRING },
    [2] = { .name = "channelWidth",   .type = BLOBMSG_TYPE_INT32 },
    [3] = { .name = "antennaGain",   .type = BLOBMSG_TYPE_INT32 },
    [4] = { .name = "pointDistance",   .type = BLOBMSG_TYPE_INT32 },
    [5] = { .name = "accessPointsNumber",   .type = BLOBMSG_TYPE_INT32 },
    [6] = { .name = "encryptionMethod",   .type = BLOBMSG_TYPE_STRING },
    [7] = { .name = "portMode",   .type = BLOBMSG_TYPE_STRING },
    [8] = { .name = "mtu",   .type = BLOBMSG_TYPE_STRING },
    [9] = { .name = "ssid",   .type = BLOBMSG_TYPE_STRING },
    [10] = { .name = "ip",   .type = BLOBMSG_TYPE_STRING },
    [11] = { .name = "mac",   .type = BLOBMSG_TYPE_STRING },

    [12] = { .name = "transmissionCapacity",   .type = BLOBMSG_TYPE_INT32 },
    [13] = { .name = "receptionThroughput",   .type = BLOBMSG_TYPE_INT32 },
    [14] = { .name = "connectTime",   .type = BLOBMSG_TYPE_INT32 },
    [15] = { .name = "sendBytes",   .type = BLOBMSG_TYPE_INT32 },
    [16] = { .name = "receivedBytes",   .type = BLOBMSG_TYPE_INT32 },

    [17] = { .name = "workingFrequency",   .type = BLOBMSG_TYPE_INT32 },
    [18] = { .name = "transmitPower",   .type = BLOBMSG_TYPE_INT32 },
    [19] = { .name = "signalStrength",   .type = BLOBMSG_TYPE_INT32 },
    [20] = { .name = "backgroundNoise",   .type = BLOBMSG_TYPE_INT32 },
    [21] = { .name = "polarizationSignalDifference",   .type = BLOBMSG_TYPE_INT32 },
    [22] = { .name = "cpu",   .type = BLOBMSG_TYPE_INT32 },
    [23] = { .name = "deviceCurrentTime",   .type = BLOBMSG_TYPE_STRING },
    [24] = { .name = "deviceName",   .type = BLOBMSG_TYPE_STRING },
    [25] = { .name = "connect", .type = BLOBMSG_TYPE_ARRAY }, //BLOBMSG_TYPE_TABLE
};



/**
 * 获取在线网桥设备
 */
int get_bridge_devices(BridgeDevice *devices, int max_count) {
    FILE *fp;
    char line[MAX_LINE_LENGTH];
    int count = 0;

    // 执行Shell脚本并读取输出
    fp = popen("/bin/bridge_scan.sh", "r"); // 替换为实际脚本路径
    if (fp == NULL) {
        perror("popen failed");
        return -1;
    }

    // 逐行读取输出
    while (count < max_count && fgets(line, sizeof(line), fp) != NULL) {
        BridgeDevice *dev = &devices[count];
        
        // 解析行数据 (格式: "时间戳|MAC|IP|线路|塔号|类型|位置")
        if (sscanf(line, "%19[^|]|%17[^|]|%15[^|]|%7[^|]|%7[^|]|%15[^|]|%15[^|]",
                   dev->timestamp, dev->mac, dev->ip, 
                   dev->line_id, dev->tower_id, dev->device_type, dev->location) == 7) {
            count++;
        } else {
            fprintf(stderr, "解析失败: %s", line);
        }
    }

    pclose(fp);
    return count; // 返回实际读取的设备数量
}
/**
 * 获取端口状态数据
 */
static void bridge_info_callback(struct ubus_request *req, int type, struct blob_attr *msg) {

    if (!msg) {
        return;
    }
    cJSON *bridgeInfo = (cJSON *)req->priv;
    // 解析内存数据
    struct blob_attr *tb[26];
    blobmsg_parse(bridge_info_policy, ARRAY_SIZE(bridge_info_policy), tb, blobmsg_data(msg), blobmsg_data_len(msg));

    if(tb[0]) EP_JSON_SET_STR(bridgeInfo, "deviceMode", blobmsg_get_string(tb[0]));
    if(tb[1]) EP_JSON_SET_STR(bridgeInfo, "wirelessMode", blobmsg_get_string(tb[1]));
    if(tb[2]) EP_JSON_SET_INT(bridgeInfo, "channelWidth", blobmsg_get_u32(tb[2]));
    if(tb[3]) EP_JSON_SET_INT(bridgeInfo, "antennaGain", blobmsg_get_u32(tb[3]));
    if(tb[4]) EP_JSON_SET_INT(bridgeInfo, "pointDistance", blobmsg_get_u32(tb[4]));
    if(tb[5]) EP_JSON_SET_INT(bridgeInfo, "accessPointsNumber", blobmsg_get_u32(tb[5]));
    if(tb[6]) EP_JSON_SET_STR(bridgeInfo, "encryptionMethod", blobmsg_get_string(tb[6]));
    if(tb[7]) EP_JSON_SET_STR(bridgeInfo, "portMode", blobmsg_get_string(tb[7]));
    if(tb[8]) EP_JSON_SET_STR(bridgeInfo, "mtu", blobmsg_get_string(tb[8]));
    if(tb[9]) EP_JSON_SET_STR(bridgeInfo, "ssid", blobmsg_get_string(tb[9]));
    // if(tb[10]) EP_JSON_SET_STR(bridgeInfo, "ip", blobmsg_get_string(tb[10]));
    // if(tb[11]) EP_JSON_SET_STR(bridgeInfo, "mac", blobmsg_get_string(tb[11]));
    if(tb[12]) EP_JSON_SET_INT(bridgeInfo, "transmissionCapacity", blobmsg_get_u32(tb[12]));
    if(tb[13]) EP_JSON_SET_INT(bridgeInfo, "receptionThroughput", blobmsg_get_u32(tb[13]));
    if(tb[14]) EP_JSON_SET_INT(bridgeInfo, "connectTime", blobmsg_get_u32(tb[14]));
    if(tb[15]) EP_JSON_SET_INT(bridgeInfo, "sendBytes", blobmsg_get_u32(tb[15]));
    if(tb[16]) EP_JSON_SET_INT(bridgeInfo, "receivedBytes", blobmsg_get_u32(tb[16]));

    if(tb[17]) EP_JSON_SET_INT(bridgeInfo, "workingFrequency", blobmsg_get_u32(tb[17]));
    if(tb[18]) EP_JSON_SET_INT(bridgeInfo, "transmitPower", blobmsg_get_u32(tb[18]));
    if(tb[19]) EP_JSON_SET_INT(bridgeInfo, "signalStrength", blobmsg_get_u32(tb[19]));
    if(tb[20]) EP_JSON_SET_INT(bridgeInfo, "backgroundNoise", blobmsg_get_u32(tb[20]));
    if(tb[21]) EP_JSON_SET_INT(bridgeInfo, "polarizationSignalDifference", blobmsg_get_u32(tb[21]));
    if(tb[22]) EP_JSON_SET_INT(bridgeInfo, "cpu", blobmsg_get_u32(tb[22]));
    if(tb[23]) EP_JSON_SET_STR(bridgeInfo, "deviceCurrentTime", blobmsg_get_string(tb[23]));
    if(tb[24]) EP_JSON_SET_STR(bridgeInfo, "deviceName", blobmsg_get_string(tb[24]));
    if(tb[25] && blobmsg_type(tb[25]) == BLOBMSG_TYPE_ARRAY) {
        printf("解析设备数组:\n");
        struct blob_attr *cur;
        size_t rem;
        int index = 0;
        cJSON *items = cJSON_CreateArray();
        blobmsg_for_each_attr(cur, tb[25], rem) {
            struct blob_attr *tb2[26];
            printf("=== Device %d ===\n", index);
            /* 解析单个设备对象 */
            blobmsg_parse(bridge_info_policy, ARRAY_SIZE(bridge_info_policy), tb2, blobmsg_data(cur), blobmsg_data_len(cur));
            cJSON *remote = cJSON_CreateObject();
            if(tb2[0]) EP_JSON_SET_STR(remote, "deviceMode", blobmsg_get_string(tb2[0]));
            if(tb2[1]) EP_JSON_SET_STR(remote, "wirelessMode", blobmsg_get_string(tb2[1]));
            if(tb2[2]) EP_JSON_SET_INT(remote, "channelWidth", blobmsg_get_u32(tb2[2]));
            if(tb2[3]) EP_JSON_SET_INT(remote, "antennaGain", blobmsg_get_u32(tb2[3]));
            if(tb2[4]) EP_JSON_SET_INT(remote, "pointDistance", blobmsg_get_u32(tb2[4]));
            if(tb2[5]) EP_JSON_SET_INT(remote, "accessPointsNumber", blobmsg_get_u32(tb2[5]));
            if(tb2[6]) EP_JSON_SET_STR(remote, "encryptionMethod", blobmsg_get_string(tb2[6]));
            if(tb2[7]) EP_JSON_SET_STR(remote, "portMode", blobmsg_get_string(tb2[7]));
            if(tb2[8]) EP_JSON_SET_STR(remote, "mtu", blobmsg_get_string(tb2[8]));
            if(tb2[9]) EP_JSON_SET_STR(remote, "ssid", blobmsg_get_string(tb2[9]));
            if(tb2[10]) EP_JSON_SET_STR(remote, "ip", blobmsg_get_string(tb2[10]));
            if(tb2[11]) EP_JSON_SET_STR(remote, "mac", blobmsg_get_string(tb2[11]));
            if(tb2[12]) EP_JSON_SET_INT(remote, "transmissionCapacity", blobmsg_get_u32(tb2[12]));
            if(tb2[13]) EP_JSON_SET_INT(remote, "receptionThroughput", blobmsg_get_u32(tb2[13]));
            if(tb2[14]) EP_JSON_SET_INT(remote, "connectTime", blobmsg_get_u32(tb2[14]));
            if(tb2[15]) EP_JSON_SET_INT(remote, "sendBytes", blobmsg_get_u32(tb2[15]));
            if(tb2[16]) EP_JSON_SET_INT(remote, "receivedBytes", blobmsg_get_u32(tb2[16]));

            if(tb2[17]) EP_JSON_SET_INT(remote, "workingFrequency", blobmsg_get_u32(tb2[17]));
            if(tb2[18]) EP_JSON_SET_INT(remote, "transmitPower", blobmsg_get_u32(tb2[18]));
            if(tb2[19]) EP_JSON_SET_INT(remote, "signalStrength", blobmsg_get_u32(tb2[19]));
            if(tb2[20]) EP_JSON_SET_INT(remote, "backgroundNoise", blobmsg_get_u32(tb2[20]));
            if(tb2[21]) EP_JSON_SET_INT(remote, "polarizationSignalDifference", blobmsg_get_u32(tb2[21]));
            if(tb2[22]) EP_JSON_SET_INT(remote, "cpu", blobmsg_get_u32(tb2[22]));
            if(tb2[23]) EP_JSON_SET_STR(remote, "deviceCurrentTime", blobmsg_get_string(tb2[23]));
            if(tb2[24]) EP_JSON_SET_STR(remote, "deviceName", blobmsg_get_string(tb2[24]));
            cJSON_AddItemToArray(items, remote);
            index++;
        }
        cJSON_AddItemToObject(bridgeInfo, "connect", items);
    }
}

int read_bridge_status_data() {
    BridgeDevice devices[MAX_DEVICES];
    int send_count = 0;
    int count = get_bridge_devices(devices, MAX_DEVICES);
    
    if (count < 0) {
        fprintf(stderr, "获取网桥设备失败\n");
        return -1;
    }

    // 连接 ubus
    struct ubus_context *ctx = ubus_connect(NULL);
    if (!ctx) {
        fprintf(stderr, "Failed to connect to ubus\n");
        return -1;
    }
    // 查找 network.device 的 ID
    uint32_t obj_id;
    if (ubus_lookup_id(ctx, "sihan.bridge", &obj_id) != 0) {
        fprintf(stderr, "Failed to lookup sihan.bridge\n");
        ubus_free(ctx);
        return -1;
    }


    printf("找到 %d 个网桥:\n", count);
    for (int i = 0; i < count; i++) {
        printf("[%d] %s | %s | %s | %s塔 | %s侧\n", i + 1, devices[i].ip, devices[i].mac, devices[i].line_id, devices[i].tower_id, devices[i].location);
    
        cJSON *root = cJSON_CreateObject();
        EP_JSON_SET_STR(root, "sn", runCfg.sn);
        EP_JSON_SET_INT(root, "loraId", runCfg.lora_addr);
        EP_JSON_SET_INT(root, "dataType", 2);
        EP_JSON_SET_INT(root, "version", 1);
        
        cJSON *bridgeData = cJSON_CreateObject();
        
        EP_JSON_SET_STR(bridgeData, "mac", devices[i].mac);
        EP_JSON_SET_STR(bridgeData, "ip", devices[i].ip);
        EP_JSON_SET_STR(bridgeData, "line_id", devices[i].line_id);
        EP_JSON_SET_STR(bridgeData, "tower_id", devices[i].tower_id);
        EP_JSON_SET_STR(bridgeData, "location", devices[i].location);
        
        blob_buf_init(&bb, 0);
        blobmsg_add_string(&bb, "ip", devices[i].ip);  // 可替换为其他接口名
        // 发起异步调用
        int ret = ubus_invoke(ctx, obj_id, "get_bridge_info", bb.head, bridge_info_callback, (void *)bridgeData, 3000);
        if (ret != 0) {
            fprintf(stderr, "ubus_invoke failed: %s\n", ubus_strerror(ret));
            continue;
        }
        sleep(1);
        cJSON_AddItemToObject(root,"data",bridgeData);
        char *str = cJSON_Print(root);
        printf("%s\n", str);
        send_data_to_mqtt(str);
        cJSON_Delete(root);
        send_count ++;
    }
    printf("发送成功 %d 个网桥\n", send_count);
    
    // 清理资源
    blob_buf_free(&bb);
    ubus_free(ctx);
    return 0;
}

//接收LoRa数据的线程
void *bridge_worker(void *param)
{
    while (1)
    {
        read_bridge_status_data();
        sleep(5 * 60);
    }
}

int bridge_worker_start() {
    if(runCfg.bridge_enable){
        pthread_t pid;
        pthread_create(&pid, NULL, (void *)bridge_worker, NULL);
    }
}

